package com.castle.fortress.admin.form.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.annotation.CastleLog;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.form.dto.ColModelDto;
import com.castle.fortress.admin.form.dto.FormConfigDto;
import com.castle.fortress.admin.form.dto.FormModelDto;
import com.castle.fortress.admin.form.entity.FormConfigEntity;
import com.castle.fortress.admin.form.service.FormConfigService;
import com.castle.fortress.admin.form.service.FormModelService;
import com.castle.fortress.admin.system.entity.DevViewListConfig;
import com.castle.fortress.admin.system.service.DevViewListConfigService;
import com.castle.fortress.admin.system.service.SysMenuService;
import com.castle.fortress.admin.utils.ExcelUtils;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.CommonUtil;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 表单配置管理 控制器
 *
 * @author castle
 * @since 2021-11-10
 */
@Api(tags="表单配置管理管理控制器")
@Controller
public class FormConfigController {
    @Autowired
    private FormConfigService formConfigService;
    @Autowired
    private FormModelService formModelService;
    @Autowired
    private DevViewListConfigService devViewListConfigService;
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 表单配置管理的分页展示
     * @param formConfigDto 表单配置管理实体类
     * @param current 当前页
     * @param size  每页记录数
     * @return
     */
    @ApiOperation("表单配置管理分页展示")
    @CastleLog(operLocation = "表单配置管理分页展示", operType = OperationTypeEnum.QUERY)
    @GetMapping("/form/formConfig/page")
    @ResponseBody
    @RequiresPermissions("form:formConfig:pageList")
    public RespBody<IPage<FormConfigDto>> pageFormConfig(FormConfigDto formConfigDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
        Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<FormConfigDto> page = new Page(pageIndex, pageSize);
        IPage<FormConfigDto> pages = formConfigService.pageFormConfigExtends(page, formConfigDto);

        return RespBody.data(pages);
    }

    /**
     * 表单配置管理的列表展示
     * @param formConfigDto 表单配置管理实体类
     * @return
     */
    @ApiOperation("表单配置管理列表展示")
    @CastleLog(operLocation = "表单配置管理列表展示", operType = OperationTypeEnum.QUERY)
    @GetMapping("/form/formConfig/list")
    @ResponseBody
    public RespBody<List<FormConfigDto>> listFormConfig(FormConfigDto formConfigDto){
        List<FormConfigDto> list = formConfigService.listFormConfig(formConfigDto);
        return RespBody.data(list);
    }

    /**
     * 表单配置管理保存
     * @param formConfigDto 表单配置管理实体类
     * @return
     */
    @ApiOperation("表单配置管理保存")
    @CastleLog(operLocation = "表单配置管理保存", operType = OperationTypeEnum.INSERT)
    @PostMapping("/form/formConfig/save")
    @ResponseBody
    @RequiresPermissions("form:formConfig:save")
    public RespBody<String> saveFormConfig(@RequestBody FormConfigDto formConfigDto){
        if(formConfigDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        FormConfigEntity formConfigEntity = ConvertUtil.transformObj(formConfigDto,FormConfigEntity.class);
        formConfigEntity.setStatus(YesNoEnum.NO.getCode());
        if(formConfigService.save(formConfigEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 表单配置管理编辑 修改表单名字和备注
     * @param formConfigDto 表单配置管理实体类
     * @return
     */
    @ApiOperation("表单配置管理编辑")
    @CastleLog(operLocation = "表单配置管理编辑", operType = OperationTypeEnum.UPDATE)
    @PostMapping("/form/formConfig/edit")
    @ResponseBody
    @RequiresPermissions("form:formConfig:edit")
    public RespBody<String> updateFormConfig(@RequestBody FormConfigDto formConfigDto){
        if(CommonUtil.verifyParamNull(formConfigDto,formConfigDto.getId(),formConfigDto.getName())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        FormConfigEntity formConfigEntity=new FormConfigEntity();
        formConfigEntity.setId(formConfigDto.getId());
        formConfigEntity.setName(formConfigDto.getName());
        formConfigEntity.setRamark(formConfigDto.getRamark());
        if(formConfigService.updateById(formConfigEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 表单配置管理编辑白名单
     * @param formConfigDto 表单配置管理实体类
     * @return
     */
    @ApiOperation("表单配置管理编辑白名单")
    @CastleLog(operLocation = "表单配置管理编辑白名单", operType = OperationTypeEnum.UPDATE)
    @PostMapping("/form/formConfig/editIp")
    @ResponseBody
    @RequiresPermissions("form:formConfig:edit")
    public RespBody<String> updateFormConfigIp(@RequestBody FormConfigDto formConfigDto){
        if(CommonUtil.verifyParamNull(formConfigDto,formConfigDto.getId())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        FormConfigEntity formConfigEntity=new FormConfigEntity();
        formConfigEntity.setId(formConfigDto.getId());
        formConfigEntity.setWhiteList(CommonUtil.emptyIfNull(formConfigDto.getWhiteList()));
        if(formConfigService.updateIpById(formConfigEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 表单设计保存
     * @param formConfigDto 表单配置管理实体类
     * @return
     */
    @ApiOperation("表单设计保存")
    @PostMapping("/form/formConfig/editDesign")
    @CastleLog(operLocation = "表单设计保存", operType = OperationTypeEnum.INSERT)
    @ResponseBody
    @RequiresPermissions("form:formConfig:editDesign")
    public RespBody<String> editDesign(@RequestBody FormConfigDto formConfigDto){
        if(CommonUtil.verifyParamNull(formConfigDto,formConfigDto.getId(),formConfigDto.getDesignContent(),formConfigDto.getTbContent(),formConfigDto.getViewContent())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        FormConfigEntity formConfigEntity = ConvertUtil.transformObj(formConfigDto,FormConfigEntity.class);
        FormConfigEntity oldConfig = formConfigService.getById(formConfigEntity.getId());
        if(oldConfig==null){
            throw new BizException(GlobalRespCode.DB_DATA_ERROR);
        }
        FormModelDto modelDto = formConfigService.convertToModel(formConfigEntity);
        //修改列表展示字段
        if(modelDto.getCols()!=null&&!modelDto.getCols().isEmpty()){
            List<DevViewListConfig> viewListConfigs=new ArrayList<>();
            for(ColModelDto c:modelDto.getCols()){
                //地区组件key值不在列表展示
                if("fortress-region".equals(c.getColTag())){
                    continue;
                }
                DevViewListConfig view=new DevViewListConfig();
                view.setTbName(formConfigEntity.getId()+"");
                view.setPropName(c.getColName());
                view.setPropDesc(StrUtil.isEmpty(c.getColComment())?c.getColName():c.getColComment());
                viewListConfigs.add(view);
            }
            QueryWrapper<DevViewListConfig> q=new QueryWrapper<>();
            q.eq("tb_name",formConfigEntity.getId()+"");
            devViewListConfigService.remove(q);
            if(!viewListConfigs.isEmpty()){
                devViewListConfigService.saveBatch(viewListConfigs);
            }
        }
        //首次设计表结构，保存表
        if(StrUtil.isEmpty(oldConfig.getTbContent())){
            //接口地址
            formConfigEntity.setUrl("formView?id="+formConfigEntity.getId());
            formConfigEntity.setSaveUrl("formManage/saveData");
            //创建表结构
            formModelService.createTable(modelDto);
            //异步保存菜单信息
            sysMenuService.saveFormMenuAsync(oldConfig.getId()+"",oldConfig.getName());
        //修改表结构
        }else if(!oldConfig.getTbContent().equals(formConfigEntity.getTbContent())){
            FormModelDto oldModelDto = formConfigService.convertToModel(oldConfig);
            modelDto.setOldCols(oldModelDto.getCols());
            //修改表结构
            formModelService.alterTable(modelDto);
            //修改查询条件
            if(StrUtil.isNotEmpty(oldConfig.getQueryCondition())){
                JSONArray conditions=new JSONArray(oldConfig.getQueryCondition());
                JSONArray conditionsNew=new JSONArray();
                JSONArray design=new JSONArray(formConfigDto.getDesignContent());
                for(int j=0;j<design.size();j++){
                    JSONObject d=design.getJSONObject(j);
                    boolean isExist=false;
                    for(int i=0;i<conditions.size();i++){
                        JSONObject o=conditions.getJSONObject(i);
                        if(d.getStr("__vModel__").equals(o.getStr("model"))){
                            isExist=true;
                            o.set("title",d.getJSONObject("__config__").getStr("label"));
                            if(!o.getStr("tag").equals(d.getJSONObject("__config__").getStr("tag"))){
                                o.set("tag",d.getJSONObject("__config__").getStr("tag"));
                                o.set("queryType","");
                                o.set("checked",false);
                            }
                            conditionsNew.add(o);
                            break;
                        }
                    }
                    if(!isExist){
                        JSONObject o=new JSONObject();
                        o.set("model",d.getStr("__vModel__"));
                        o.set("title",d.getJSONObject("__config__").getStr("label"));
                        o.set("tag",d.getJSONObject("__config__").getStr("tag"));
                        o.set("queryType","");
                        o.set("checked",false);
                        conditionsNew.add(o);
                    }
                }
                formConfigEntity.setQueryCondition(conditionsNew.isEmpty()?"":conditionsNew.toString());
            }
        }
        if(formConfigService.updateById(formConfigEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 表格设计保存
     * @param formConfigDto 表单配置管理实体类
     * @return
     */
    @ApiOperation("表格设计保存")
    @CastleLog(operLocation = "表格设计保存", operType = OperationTypeEnum.INSERT)
    @PostMapping("/form/formConfig/editTableDesign")
    @ResponseBody
    @RequiresPermissions("form:formConfig:editTableDesign")
    public RespBody<String> editTableDesign(@RequestBody FormConfigDto formConfigDto){
        if(CommonUtil.verifyParamNull(formConfigDto,formConfigDto.getId(),formConfigDto.getQueryCondition())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        FormConfigEntity oldConfig = formConfigService.getById(formConfigDto.getId());
        if(oldConfig==null){
            throw new BizException(GlobalRespCode.DB_DATA_ERROR);
        }
        FormConfigEntity formConfigEntity=new FormConfigEntity();
        formConfigEntity.setId(formConfigDto.getId());
        formConfigEntity.setQueryCondition(formConfigDto.getQueryCondition());
        if(formConfigService.updateById(formConfigEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 表单配置管理删除
     * @param id
     * @return
     */
    @ApiOperation("表单配置管理删除")
    @CastleLog(operLocation = "表单配置管理删除", operType = OperationTypeEnum.DELETE)
    @PostMapping("/form/formConfig/delete")
    @ResponseBody
    @RequiresPermissions("form:formConfig:delete")
    public RespBody<String> deleteFormConfig(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(formConfigService.removeById(id)) {
            //删除表结构
            formModelService.dropTable("castle_form"+id);
            //删除菜单及角色关联
            sysMenuService.delFormMenuAsync(id+"");
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 表单配置管理批量删除
     * @param ids
     * @return
     */
    @ApiOperation("表单配置管理批量删除")
    @PostMapping("/form/formConfig/deleteBatch")
    @CastleLog(operLocation = "表单配置管理批量删除", operType = OperationTypeEnum.DELETE)
    @ResponseBody
    @RequiresPermissions("form:formConfig:deleteBatch")
    public RespBody<String> deleteFormConfigBatch(@RequestBody List<Long> ids){
        if(ids == null || ids.size()<1){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(formConfigService.removeByIds(ids)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 表单配置管理详情
     * @param id 表单配置管理id
     * @return
     */
    @ApiOperation("表单配置管理详情")
    @CastleLog(operLocation = "表单配置管理详情", operType = OperationTypeEnum.QUERY)
    @GetMapping("/form/formConfig/info")
    @ResponseBody
    public RespBody<FormConfigDto> infoFormConfig(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        FormConfigDto formConfigDto =  formConfigService.getByIdExtends(id);

        return RespBody.data(formConfigDto);
    }

    /**
     * 表单访问状态切换
     * @param id 表单配置管理id
     * @return
     */
    @ApiOperation("表单访问状态切换")
    @CastleLog(operLocation = "表单访问状态切换", operType = OperationTypeEnum.OTHER)
    @GetMapping("/form/formConfig/statusChange")
    @ResponseBody
    @RequiresPermissions("form:formConfig:statusChange")
    public RespBody<String> statusChange(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        FormConfigEntity entity =  formConfigService.getById(id);
        if(entity==null){
            throw new BizException(GlobalRespCode.DB_DATA_ERROR);
        }
        entity.setStatus(YesNoEnum.YES.getCode().equals(entity.getStatus())?YesNoEnum.NO.getCode() : YesNoEnum.YES.getCode());
        if(formConfigService.updateById(entity)){
            return RespBody.data("保存成功");
        }else{
            throw new BizException(GlobalRespCode.OPERATE_ERROR);
        }
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation = "表单配置管理导出", operType = OperationTypeEnum.EXPORT)
	@PostMapping("/form/formConfig/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<FormConfigDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<FormConfigDto> list = formConfigService.listFormConfig(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}


}
